package com.autoplaza;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DatosContacto extends Activity {
	Bundle extras;
	String nombre,email,telefonos,hora1,hora2,encabezado,marcadotelefonos, marca, modelo, year, idanuncio;
	TextView nombrecontacto,telcontacto,horainicial,horafinal,txtencabezado;
	Button llamarcontacto,emailcontacto;
	String[] ntel;
	Dialog dialog;
	LinearLayout lin;
	LinearLayout ll;
	String id;
	Button[] btarray;
	Button bt;
	TextView numtel;
	int resID;
	int j;
	String[] telefonosarray;
	String[] marcaTel;
	private ProgressDialog progressDialog;
	InputStream is = null;
	String[] array;
	String result;


	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.datoscontacto);
		
		int size = Utils.getScreenSize2(DatosContacto.this);
		if( size == 1){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(30, 30));
		}		
		if( size == 2){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60));	
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(45, 45));

		}		
		if( size == 3){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 80));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(80, 80));

		}
		
		nombrecontacto=(TextView) findViewById(R.id.nombrecontacto);
		telcontacto=(TextView) findViewById(R.id.telefonoscontacto);
		horainicial=(TextView) findViewById(R.id.horainicial);
		horafinal=(TextView) findViewById(R.id.horafinal);
		txtencabezado=(TextView) findViewById(R.id.encabezado);
		llamarcontacto=(Button) findViewById(R.id.llamarcontacto);
		emailcontacto=(Button) findViewById(R.id.emailcontacto);

		extras=getIntent().getExtras();
		if(extras != null){
			
			
			new CargarInfo().execute("");
			
			
		}else{
			finish();
		}
		
	}
	
	
	protected void crearDialog() {
		
		dialog=new Dialog(DatosContacto.this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    	dialog.setContentView(R.layout.customdialog);
    	dialog.show();

    	ll=(LinearLayout)dialog.findViewById(R.id.linearllamada);
    	Button btcancel=(Button) dialog.findViewById(R.id.btcancelar);
    	btcancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				dialog.cancel();
			}
		});
    	marcaTel=marcadotelefonos.split("%%%");
		telefonosarray=telefonos.split(",");
		btarray=new Button[telefonosarray.length];
		for(int i=0;i<telefonosarray.length;i++){
			j=i;
				if(telefonosarray[i].trim().startsWith("ID")){
				
			}else{
				RelativeLayout relative=new RelativeLayout(this);
				relative.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				
				LinearLayout lintel=new LinearLayout(this);
				lintel.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				lintel.setOrientation(LinearLayout.VERTICAL);
				String[] telarray=telefonosarray[i].split(":");
				TextView tipo=new TextView(this);
				tipo.setText(""+telarray[0]);
				tipo.setTypeface(null,Typeface.BOLD);
				tipo.setTextColor(Color.RED);

				TextView numero=new TextView(this);
				numero.setText(""+telarray[1]);
				numero.setTypeface(null,Typeface.BOLD);
				numero.setTextColor(Color.BLACK);

				lintel.addView(tipo);
				lintel.addView(numero);
				
				bt=new Button(this);
				bt.setBackgroundResource(R.drawable.selectorllamada);
				bt.setOnClickListener(getOnClickDoSomething(bt, ""+marcaTel[i]));
				
				relative.addView(lintel);
				relative.addView(bt);
				
				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)lintel.getLayoutParams();
				params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				lintel.setLayoutParams(params); //causes layout update
				
				RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams)bt.getLayoutParams();
				params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
				bt.setLayoutParams(params2);
				
				ll.addView(relative);
				
			}
		}

	}

	View.OnClickListener getOnClickDoSomething(final Button button, final String texto)  {
	    return new View.OnClickListener() {
	        public void onClick(View v) {

	        	Intent callIntent = new Intent();
			     callIntent = new Intent(Intent.ACTION_DIAL,
							Uri.parse("tel:"+texto));
			     			     
			     startActivity(callIntent);	
	        }
	    };
	}
	
	@Override  
    public boolean onContextItemSelected(MenuItem item) {  
		String[] marcaTel=marcadotelefonos.split("%%%");
		for(int i=0;i<ntel.length;i++){
			if(item.getTitle().equals(ntel[i])){
			     Intent callIntent = new Intent();
			     callIntent = new Intent(Intent.ACTION_DIAL,
							Uri.parse("tel:"+marcaTel[i]));
			     			     
			     startActivity(callIntent);		
			     
			     
			}
		}
		
    return true;  
    }  

	
	public boolean isNetwork(){
		NetworkInfo networkInfo = ((ConnectivityManager) getApplicationContext()
	              .getSystemService(Context.CONNECTIVITY_SERVICE))
	              .getActiveNetworkInfo();

	            if(networkInfo == null || !networkInfo.isConnected()) {
	             return false;
	            }
	            return true;
    }
    
	private void dialogoInternet() {
		AlertDialog.Builder builder = new AlertDialog.Builder(DatosContacto.this);
		builder.setMessage("Necesita conexión a Internet")
		       .setCancelable(false)
		       .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		           }
		       });
		AlertDialog alertDialog = builder.create();
		alertDialog.show();		
								
	}
	
	
	public class CargarInfo extends AsyncTask<String, String, String>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(DatosContacto.this, "",
					"Cargando...", true, true, new OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface arg0) {
							finish();
						}
			});
		}
		
		
		@Override
		protected String doInBackground(String... params) {
			if(extras.getString("from").equals("lista")){
				metodoinformacion(extras.getString("numauncio"));
				nombre = array[22];
				email = array[23];
				telefonos = array[24];
				hora1 = array[29];
				hora2 = array[30];
				encabezado = array[4]+" "+array[0]+" "+array[3];
				marcadotelefonos = array[56];
				marca = array[4];
				modelo = array[0];
				year = array[3];
				idanuncio = array[1];
				
				
			}else{
				nombre=extras.getString("nombre");
				email=extras.getString("email");
				telefonos=extras.getString("telefonos");
				hora1=extras.getString("hora1");
				hora2=extras.getString("hora2");
				encabezado=extras.getString("encabezado");
				marcadotelefonos=extras.getString("marcadotelefonos");
				marca=extras.getString("marca");
				modelo=extras.getString("modelo");
				year=extras.getString("year");
				idanuncio=extras.getString("idanuncio");
				
			}
			
			
			
			
			

		
			
			
			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			txtencabezado.setText(encabezado);
			nombrecontacto.setText(nombre);
			String[] telefonosarray=telefonos.split(",");
			StringBuilder sb=new StringBuilder();
			for(int i=0;i<telefonosarray.length;i++){
				if(telefonosarray[i].trim().startsWith("ID")){
					
				}else{
					String[] arrayTel=telefonosarray[i].split(":");
					sb.append(telefonosarray[i]+"\n");
				}
			}
			telcontacto.setText(sb.toString());

			if(hora1.equals("null")){
				horainicial.setText("---");
			}else{
				horainicial.setText(hora1);
			}
			if(hora2.equals("null")){
				horafinal.setText("---");

			}else{
				horafinal.setText(hora2);
			}
			
			
			
			llamarcontacto.setOnClickListener(new OnClickListener() {	
				@Override
				public void onClick(View arg0) {
					if(isNetwork()==true){
						crearDialog();
					}else{
						dialogoInternet();
					}
				}
			});
			emailcontacto.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(isNetwork()==true){
						Intent irEmail=new Intent(DatosContacto.this, ContactoEmail.class);
						irEmail.putExtra("idanuncio", ""+idanuncio);
						irEmail.putExtra("marca", ""+marca);
						irEmail.putExtra("modelo", ""+modelo);
						irEmail.putExtra("year", ""+year);
						startActivity(irEmail);
					}else{
						dialogoInternet();
					}
					
				}
			});
			
			
			
			progressDialog.dismiss();

		}
		
		
	}
	
	
	private void metodoinformacion(String numanuncio2) {
	     String url="http://iphone.autoplaza.com.mx/fastSearch/fastSearchIphone.aspx?querybiphone=yes&id="+numanuncio2+"&News=yes";
	        Log.i("url mia", ""+url);
			
			URI myURI = null;
			try {
				myURI = new URI(url);
			} catch (URISyntaxException e) {
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
			try {
				webServerResponse = httpClient.execute(getMethod);
			}  catch (IOException e) {
			}
			
			HttpEntity httpEntity = webServerResponse.getEntity();
	       
			
			if (httpEntity != null) {
		
				try {
					is = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
		            StringBuilder sb = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null) {
		                    sb.append(line + "\n");
		            }
		            is.close();
		            result=sb.toString().trim();
//		    		array2=new String[1];
//		    		array3=new String[6];
		            array=result.split("@@@");
			           Log.i("TAM ARRAY", ""+array.length);

		            
//		           array2 = array[18].split("T");
		           
		           
//		           if(array.length == 60){
//			           array3 = array[57].split("%%%");
//			            for(int i=0; i<array3.length; i++){
//			            	Log.i("MI ARRAY3["+i+"]", ""+array3[i]);
//			            }
//			            noNoticia=1;
//		        	   
//		           }
		           
		           

		            for(int i=0; i<array.length; i++){
		            	Log.i("MI ARRAY1["+i+"]", ""+array[i]);
		            }
//		            for(int i=0; i<array2.length; i++){
//		            	Log.i("MI ARRAY2["+i+"]", ""+array2[i]);
//		            }


				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
				}
			}
			
			
		
			
	}

	
	
	
	

}
